<template>
  <div class="wap">
    <edu-calendar ref="eduCalendar" v-if="isShowCalendar" :dateMasksList="dateMasksList" @getSelectDate="getSelectDate" @getScheduleDate="getScheduleDate" class="c-pf c-w100 c-bg-white c-pz99" :class="unenableTopNav ? 'c-p-t0' : 'c-p-t68'"></edu-calendar>
    <!-- 列表 -->
    <div class="c-ph24 c-pt180 c-minh80vh">
      <div
        class="c-pv30 c-bd-b1"
        v-for="(item, index) in scheduleList"
        :key="index"
        @click="handleClickDetails(item.id)"
      >
        <div class="c-flex-row">
          <div class="c-ww210 c-hh140 c-p c-br10">
            <img
              class="c-w100 c-maxh140 c-br10 "
              :class="{'imgGray':timestamp(item.endTime) <= timestamp(getDate(2))}"
              :src="$addXossFilter(item.image, require('../../assets/default-course.png'))"
              alt=""
            >
          </div>
          <div class="c-flex-column c-pl20 c-flex-grow1 c-w0 c-pv4 c-justify-sb">
            <div
              class="c-fs24 c-text-ellipsis1 "
              :class="timestamp(item.endTime) <= timestamp(getDate(2)) ? 'c-fc-gray':'c-fc-xblack'"
            >{{item.courseName}}</div>
            <div class="c-fs20 c-text-ellipsis1 c-fc-gray">学员数：{{item.studentNum}}</div>
            <div class="c-fs20 c-fc-gray">
              <template v-if="isSameDay(item.startTime, item.endTime)">
                <span>{{item.newTime.first}}</span>
                <span class="c-ph5">{{'('+`${item.newTime.second}`+')'}}</span>
                <span>{{item.newTime.third}}</span>
              </template>
              <template v-else>
                <span>{{item.startTime}}</span>
                <span class="c-ph5">-</span>
                <span>{{item.endTime}}</span>
              </template>
            </div>
          </div>
        </div>
        <div class="c-fs20 c-text-ellipsis1 c-fc-gray c-mt32" v-if="item.provinceName != null && item.cityNam != null && item.areaName != null && item.details != null">
          <i class="iconfont c-fs20">&#xe90f;</i>
          <span>上课地点：{{item.provinceName+item.cityName+item.areaName+item.details}}</span>
        </div>
      </div>
      <div v-if="isStudent" class="c-pf c-p-b220 c-pz100 c-p-r0 c-ww100 c-hh42 c-lh42 c-bg-white theme-fc c-br-tl20 c-br-bl20 c-fs20 c-textAlign-c c-pz10 c-box-shadowEdu" @click="goFaceTeaching">学员端</div>
      <loading-status-tem
        :dataStatus="dataStatus"
        noDataText="您暂时没有课程"
      ></loading-status-tem>
    </div>
    <nav-bottom-bar :itemIndex="24" v-if="showNavBottomBar"></nav-bottom-bar>
  </div>
</template>

<script>
import { utilJs } from "@/utils/common.js";
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import NavBottomBar from "@/components/templates/common/navBottomBar.vue";
import EduCalendar from "@/components/templates/edu/eduCalendar.vue";
export default {
  name: 'CourseManagment',
  components: {
    loadingStatusTem,
    NavBottomBar,
    EduCalendar
  },
  data() {
    return {
      startDate: "1920-01-01", //默认从2000年起
      endDate: "",
      dataStatus: 'HAS_MORE_DATA',
      scheduleList: [],
      showNavBottomBar: false,
      companyAuth: null,
      isStudent: false, // 是否同时是学生
      isShowCalendar: true, // 是否显示日历，用于刷新日历数据
      dateMasksList: [], // 有预约课程的日期列表
      startTime: '', // 筛选时间，开始
      endTime: '', // 筛选时间，结束
    }
  },
  computed: {
    // 判断是否跨天
    isSameDay() {
      return function (start, end) {
        let startTime = new Date(start);
        let endTime = new Date(end);
        let isSameDay = startTime.getFullYear() == endTime.getFullYear() && startTime.getMonth() == endTime.getMonth() && startTime.getDate() == endTime.getDate();
        return isSameDay;
      }
    },
    // 判断是否有顶部导航
    unenableTopNav() {
      const companyAuth = localStorage.getItem("companyAuth") ? JSON.parse(localStorage.getItem("companyAuth")) : {};
      return companyAuth && companyAuth.companyTopNav && companyAuth.companyTopNav.style && companyAuth.companyTopNav.style == 5
    },
  },
  watch: {
    $route(to, from) {
      this.isShowCalendar = false;
    }
  },
  async activated() {
    setDocumentTitle("课程列表");
    const res = await this.checkUserRole()
    if (res && res.role == 1) {
      this.$routerGo(this, "push", { path: "/edu/faceTeaching" });
      return;
    }
    this.$nextTick(() => {
      this.isShowCalendar = true;
    })
    this.companyAuth = JSON.parse(localStorage.getItem("companyAuth"));
    if (this.companyAuth.companyNav && this.companyAuth.companyNav.length > 0) {
      let arrCampFilter = this.companyAuth.companyNav.filter((item) => {
        return item.navType == 24;
      });
      this.showNavBottomBar = arrCampFilter.length > 0;
    }
    let today = utilJs.getNowTimeFormat('YYYY-MM-DD');
    this.startTime = today;
    this.endTime = this.startTime;
    this.scheduleList = [];
    this.dateMasksList = [];
    this.getScheduleDate(this.startTime);
    this.getScheduleList()
    this.wechatShare();
  },
  creadted() {
    utilJs.appShare(this);
  },
  methods: {
    checkUserRole() {
      return new Promise((resolve, reject) => {
        utilJs.getMethod(global.apiurl + 'educationSystem/mentor/teacher/checkUserRole', res => {
          localStorage.setItem("jwRole", res.role);
          this.isStudent = res.isStudent
          resolve(res)
        }, failRes => {
          reject(failRes)
        })
      })
    },
    goFaceTeaching() {
      localStorage.setItem("jwRole", 1)
      this.$routerGo(this, "push", { path: '/edu/faceTeaching' });
    },
    handleClickDetails(id) {
      // 跳转详情
      this.$routerGo(this, "push", {
        path: "/edu/courseManagmentDetail",
        query: { id: id }
      });
    },
    timestamp(date) {
      let thisTime = date.replace(/\-/g, "/");
      thisTime = new Date(thisTime).getTime();
      return thisTime;
    },
    // 获取选中的时间范围
    getSelectDate(item) {
      if (!item) {
        return
      }
      window.scrollTo(0, 0);
      this.startTime = item.startTime;
      this.endTime = item.endTime;
      this.dateMasksList = [];
      this.dataStatus = 'HAS_MORE_DATA';
      this.getScheduleDate(this.startTime);
      this.getScheduleList()
    },
    // 获取列表日历数据
    getScheduleDate(startTime) {
      let startYears = Number(startTime.split('-')[0])
      let startMonth = Number(startTime.split('-')[1])
      let startDate = startMonth > 1 ? (startYears + '-' + ((startMonth - 1) >= 10 ? (startMonth - 1) : ('0' + (startMonth - 1))) + '-01') : ((startYears - 1) + '-12-01');
      let endDate = startMonth < 12 ? (startYears + '-' + ((startMonth + 1) >= 10 ? (startMonth + 1) : ('0' + (startMonth + 1))) + '-' + utilJs.getMonthDays(startYears, startMonth + 1)) : ((startYears + 1) + '-01-31');
      utilJs.getMethod(global.apiurl + `educationSystem/mentor/teacher/scheduleList?type=2&beginTime=${startDate}&endTime=${endDate}&limit=93`, res => {
        this.dateMasksList = [];
        if (res && res.length > 0) {
          res.forEach((item, index) => {
            this.dateMasksList.push({
              year: Number(item.startDate.split('-')[0]),
              month: Number(item.startDate.split('-')[1]),
              date: Number(item.startDate.split('-')[2]),
            })
          })
        }
      }, failRes => {});
    },
    getScheduleList() {
      // 获取列表数据
      this.scheduleList = [];
      this.dataStatus = 'LOADING';
      utilJs.getMethod(global.apiurl + `educationSystem/mentor/teacher/scheduleList?type=1&beginTime=${this.startTime}&endTime=${this.endTime}`, res => {
        if (res.length > 0) {
          this.scheduleList = res;
          this.dataStatus = 'NO_MORE_DATA';
        } else {
          this.dataStatus = 'NO_DATA';
        }
      },
        failRes => {
          this.dataStatus = 'DATA_ERROR';
        }
      );
    },
    getDate(type) {
      const date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      let hour = date.getHours();
      let minute = date.getMinutes();
      let second = date.getSeconds();
      month = month > 9 ? month : '0' + month;
      day = day > 9 ? day : '0' + day;
      if (type == 1) {
        return `${year}-${month}-${day}`;
      } else {
        return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
      }
    },
    //分享
    wechatShare: function () {
      let title = '课程管理';
      let shareImg = window.localStorage.getItem("shareLogo");
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = '点击查看详情';
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc);
    },
    //手机端分享
    appShare: function () {
      let title = '课程管理';
      let shareImg = window.localStorage.getItem("shareLogo");
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = '点击查看详情';
      utilJs.appShareTrue(title, shareImg, shareUrl, shareDesc);
    },
  },
}
</script>

<style scoped>
.selectDate >>> .vux-cell-value {
  color: #333333;
}
.selectDate >>> .vux-input-icon {
  display: none !important;
}
.selectDate >>> .weui-cell__ft {
  padding: 0 !important;
}
.selectDate >>> .weui-cell {
  padding: 0 !important;
}
.selectDate >>> .weui-cell__ft:after {
  display: none !important;
}
.imgGray {
  -webkit-filter: grayscale(1); /* Webkit */
  filter: gray; /* IE6-9 */
  filter: grayscale(1); /* W3C */
}
</style>